package org.jeecg.modules.xl.product.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.xl.exceltemplate.vo.ProductCustomer;
import org.jeecg.modules.xl.product.entity.XlProductCustomerPrice;
import org.jeecg.modules.xl.product.entity.XlProductInfo;
import org.jeecg.modules.xl.product.entity.XlProductPics;
import org.jeecg.modules.xl.product.service.IXlProductCustomerPriceService;
import org.jeecg.modules.xl.product.service.IXlProductInfoService;
import org.jeecg.modules.xl.product.service.IXlProductPicsService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 客户商品
 *
 * @author deco
 * @create 2025-01-07
 */
@Api(tags="productcustomer")
@RestController
@RequestMapping("/xl/productcustomer")
@Slf4j
public class XlProductCustomer {
    @Autowired
    private IXlProductInfoService xlProductInfoService;
    @Autowired
    private IXlProductPicsService xlProductPicsService;
    @Autowired
    private IXlProductCustomerPriceService xlProductCustomerPriceService;
    @Value("${pichost}")
    private String baseUrl;
    /**
     * 分页列表查询
     *
     * @param xlProductInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "xl_product_info-分页列表查询")
    @ApiOperation(value="xl_product_info-分页列表查询", notes="xl_product_info-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<XlProductInfo>> queryPageList(XlProductInfo xlProductInfo,
                                                      @RequestParam(name="noIds", required=false) String noIds,
                                                      @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                      @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                      HttpServletRequest req) {
        // 自定义查询规则
        Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
        // 自定义多选的查询规则为：LIKE_WITH_OR
        customeRuleMap.put("status", QueryRuleEnum.LIKE_WITH_OR);
        QueryWrapper<XlProductInfo> queryWrapper = QueryGenerator.initQueryWrapper(xlProductInfo, req.getParameterMap(),customeRuleMap);

        //过滤id集合，这段代码只用于创建订单时，商品选择
        if (StringUtils.isNotBlank(noIds)){
            queryWrapper.notIn("id", noIds.split(","));
            queryWrapper.notIn("upc_code", noIds.split(","));
        }

        if(ObjectUtil.isEmpty(xlProductInfo.getType())){
            return Result.error("请先选择渠道类型");
        }
        queryWrapper.eq("type",xlProductInfo.getType());
        Page<XlProductInfo> page = new Page<XlProductInfo>(pageNo, pageSize);
        IPage<XlProductInfo> pageList = xlProductCustomerPriceService.queryListByPage(page, queryWrapper);
        //String baseUrl = "http://47.93.163.105:8058/jeecg-boot/sys/common/static/";
        List<XlProductInfo> newRecordsList = new ArrayList<>();
        for(XlProductInfo xlProductInfoTemp : pageList.getRecords()){
            if(ObjectUtil.isNotEmpty(xlProductInfoTemp.getMainPic())) {
                xlProductInfoTemp.setMainPic(baseUrl + xlProductInfoTemp.getMainPic());
            }else{
                xlProductInfoTemp.setMainPic(baseUrl+ "/temp/nophoto.png");
            }
            newRecordsList.add(xlProductInfoTemp);
        }
        pageList.setRecords(newRecordsList);
        return Result.OK(pageList);
    }

    /**
     *   添加
     *
     * @param xlProductInfoPage
     * @return
     */

    @RequiresPermissions("org.jeecg.modules.xl:xl_product_info:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody XlProductInfo xlProductInfoPage) {
        QueryWrapper<XlProductInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("upc_code",xlProductInfoPage.getUpcCode());
        XlProductInfo  xlProductInfo = xlProductInfoService.getOne(queryWrapper);
        if(ObjectUtil.isEmpty(xlProductInfo)){
            return Result.error("upc_code不存在，添加失败！");
        }
        XlProductCustomerPrice priceEntity = new XlProductCustomerPrice();
        BeanUtils.copyProperties(xlProductInfo,priceEntity);
        priceEntity.setId(null);
        priceEntity.setSupplyPrice(xlProductInfoPage.getSupplyPrice());
        priceEntity.setProductId(xlProductInfo.getId());
        priceEntity.setType(xlProductInfoPage.getType());
        xlProductCustomerPriceService.save(priceEntity);
        return Result.OK("添加成功！");
    }

    /**
     *  编辑
     *
     * @param xlProductInfoPage
     * @return
     */

    @RequiresPermissions("org.jeecg.modules.xl:xl_product_info:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<String> edit(@RequestBody XlProductInfo xlProductInfoPage) {
        XlProductCustomerPrice xlProductCustomerPrice = new XlProductCustomerPrice();
        xlProductCustomerPrice.setId(xlProductInfoPage.getId());
        xlProductCustomerPrice.setSupplyPrice(xlProductInfoPage.getSupplyPrice());
        xlProductCustomerPriceService.updateById(xlProductCustomerPrice);

        return Result.OK("编辑成功!");
    }

    /**
     *   通过id删除
     *
     * @param id
     * @return
     */
    @RequiresPermissions("org.jeecg.modules.xl:xl_product_info:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name="id",required=true) String id) {
        //xlProductInfoService.delMain(id);
        xlProductCustomerPriceService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     *  批量删除
     *
     * @param ids
     * @return
     */
    @RequiresPermissions("org.jeecg.modules.xl:xl_product_info:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.xlProductInfoService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "xl_product_info-通过id查询")
    @ApiOperation(value="xl_product_info-通过id查询", notes="xl_product_info-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<XlProductInfo> queryById(@RequestParam(name="id",required=true) String id) {
        XlProductInfo xlProductInfo = xlProductInfoService.getById(id);
        if(xlProductInfo==null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(xlProductInfo);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "产品图片通过主表ID查询")
    @ApiOperation(value="产品图片主表ID查询", notes="产品图片-通主表ID查询")
    @GetMapping(value = "/queryXlProductPicsByMainId")
    public Result<List<XlProductPics>> queryXlProductPicsListByMainId(@RequestParam(name="id",required=true) String id) {
        List<XlProductPics> xlProductPicsList = xlProductPicsService.selectByMainId(id);
        return Result.OK(xlProductPicsList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param xlProductInfo
     */
    @RequiresPermissions("org.jeecg.modules.xl:xl_product_info:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, XlProductInfo xlProductInfo) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<XlProductInfo> queryWrapper = QueryGenerator.initQueryWrapper(xlProductInfo, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if(oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id",selectionList);
        }
        queryWrapper.eq("type",xlProductInfo.getType());//不存在的数据库字段，需要手动设置
        //Step.2 获取导出数据
        Page<XlProductInfo> page = new Page<XlProductInfo>(1, 500);
        Page<XlProductInfo>  xlProductInfoPageList = xlProductCustomerPriceService.queryListByPage(page,queryWrapper);
        List<XlProductInfo> xlProductInfoList = xlProductInfoPageList.getRecords();
        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "xl_product_info列表");
        mv.addObject(NormalExcelConstants.CLASS, XlProductInfo.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("xl_product_info数据", "导出人:"+sysUser.getRealname(), "xl_product_info"));
        mv.addObject(NormalExcelConstants.DATA_LIST, xlProductInfoList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("org.jeecg.modules.xl:xl_product_info:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setSheetNum(1);	//只导入一个sheet数据
            params.setStartSheetIndex(0);	//从第一个sheet开始导入
            params.setNeedSave(false);
            try {
                List<ProductCustomer> list = ExcelImportUtil.importExcel(file.getInputStream(), ProductCustomer.class, params);
                //去重
                // 使用 Stream + HashSet 去重
                Set<String> seen = new HashSet<>();
                List<ProductCustomer> distinctList = list.stream()
                        .filter(p -> seen.add(p.getType()+p.getUpcCode())) // 如果 upccode 已存在，返回 false
                        .collect(Collectors.toList());
                // 处理
                Map<String,XlProductInfo> productInfoMap = new HashMap<>();
                for (ProductCustomer dto : distinctList) {
                    ///查询所有的商品主档
                   QueryWrapper<XlProductInfo> queryWrapper = new QueryWrapper<>();
                   queryWrapper.eq("upc_code", dto.getUpcCode());

                   XlProductInfo xlProductInfoTemp =null;
                   if(ObjectUtil.isNotEmpty(productInfoMap.get(dto.getUpcCode()))){
                       xlProductInfoTemp = productInfoMap.get(dto.getUpcCode());
                   }else{
                       xlProductInfoTemp = xlProductInfoService.getOne(queryWrapper);
                       productInfoMap.put(dto.getUpcCode(),xlProductInfoTemp);
                   }
                   if(ObjectUtil.isEmpty(xlProductInfoTemp)){
                       continue;
                   }
                    XlProductCustomerPrice priceEntity = new XlProductCustomerPrice();
                    BeanUtils.copyProperties(xlProductInfoTemp,priceEntity);
                    priceEntity.setId(null);
                    priceEntity.setSupplyPrice(dto.getSupplyPrice());
                    priceEntity.setProductId(xlProductInfoTemp.getId());
                    priceEntity.setType(dto.getType());
                    xlProductCustomerPriceService.insertOrUpdate(priceEntity);
//                    //更新cover_customer字段
//                    if(ObjectUtil.isEmpty(xlProductInfoTemp.getCoverCustomer())){
//                        xlProductInfoTemp.setCoverCustomer(dto.getType());
//                    }else{
//                        xlProductInfoTemp.setCoverCustomer(xlProductInfoTemp.getCoverCustomer()+","+dto.getType());
//                    }
//                    xlProductInfoService.updateById(xlProductInfoTemp);
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(),e);
                return Result.error("文件导入失败:"+e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

}

